package controllers;

import helpers.PaginatorHelper;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entities.Webmail;
import entities.Website;

import models.WebmailModel;
import models.WebsiteModel;

public class WebmailListServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		int page = 1;
		int limit = 20;
		try {
			page = Integer.parseInt((String) request.getParameter("page"));
		} catch (Exception e) {}
		
		WebmailModel webmailModel = WebmailModel.getInstance();
		List<Webmail> webmails = webmailModel.list(page, limit);
		boolean nextPage = false;
		boolean prevPage = false;
		
		if (webmails.size() == limit) {
			nextPage = true;
		}
		
		if (page > 1) {
			prevPage = true;
		}
		
		//Get paginate
		String queryString = request.getQueryString();
		String requestURI = request.getRequestURI();
		PaginatorHelper paginator = new PaginatorHelper(queryString);
		paginator.setUrl(requestURI);
		
		List<String> ids = new ArrayList<String>();
		for (int i = 0; i < webmails.size(); i++) {
			if (webmails.get(i) != null) {
				ids.add(webmails.get(i).getId());
			}
		}
		
		WebsiteModel websiteModel = WebsiteModel.getInstance();
		Map<String, Website> websites = websiteModel.getByListId(ids);
		
		if (websites == null) {
			websites = new TreeMap<String, Website>();
		}
		
		request.setAttribute("webmails", webmails);
		request.setAttribute("websites", websites);
		request.setAttribute("paginator", paginator);
		request.setAttribute("prevPage", prevPage);
		request.setAttribute("nextPage", nextPage);
		request.setAttribute("page", page);
		try {
			request.getRequestDispatcher("/pages/webmail_list.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
